// utils/recorder.js

/**
 * 录音管理器封装 - uni-app版本
 */
export default class RecorderManager {
  constructor() {
    this.recorderManager = uni.getRecorderManager();
    this.innerAudioContext = uni.createInnerAudioContext();
    this.tempFilePath = '';
    this.isRecording = false;
    this.isPlaying = false;
    
    // 设置录音结束回调
    this.recorderManager.onStop((res) => {
      this.tempFilePath = res.tempFilePath;
      this.isRecording = false;
      if (this.onRecordEnd) {
        this.onRecordEnd(res.tempFilePath);
      }
    });
    
    // 设置录音错误回调
    this.recorderManager.onError((res) => {
      this.isRecording = false;
      if (this.onError) {
        this.onError(res);
      }
    });
    
    // 设置播放结束回调
    this.innerAudioContext.onEnded(() => {
      this.isPlaying = false;
      if (this.onPlayEnd) {
        this.onPlayEnd();
      }
    });
    
    // 设置播放错误回调
    this.innerAudioContext.onError((res) => {
      this.isPlaying = false;
      if (this.onError) {
        this.onError(res);
      }
    });
  }
  
  /**
   * 开始录音
   */
  startRecord() {
    if (this.isRecording) return;
    
    const options = {
      duration: 60000, // 最长录音时间，单位ms
      sampleRate: 16000, // 采样率
      numberOfChannels: 1, // 录音通道数
      encodeBitRate: 48000, // 编码码率
      format: 'mp3', // 音频格式
      frameSize: 50 // 指定帧大小
    };
    
    this.recorderManager.start(options);
    this.isRecording = true;
  }
  
  /**
   * 停止录音
   */
  stopRecord() {
    if (!this.isRecording) return;
    this.recorderManager.stop();
  }
  
  /**
   * 播放录音
   * @param {string} filePath - 可选，音频文件路径，默认播放最近一次录音
   */
  playRecord(filePath) {
    if (this.isPlaying) {
      this.innerAudioContext.stop();
    }
    
    const audioPath = filePath || this.tempFilePath;
    if (!audioPath) {
      if (this.onError) {
        this.onError({ errMsg: '没有可播放的录音' });
      }
      return;
    }
    
    this.innerAudioContext.src = audioPath;
    this.innerAudioContext.play();
    this.isPlaying = true;
  }
  
  /**
   * 停止播放
   */
  stopPlay() {
    if (!this.isPlaying) return;
    this.innerAudioContext.stop();
    this.isPlaying = false;
  }
  
  /**
   * 设置录音结束回调
   * @param {Function} callback - 回调函数
   */
  setOnRecordEnd(callback) {
    this.onRecordEnd = callback;
  }
  
  /**
   * 设置播放结束回调
   * @param {Function} callback - 回调函数
   */
  setOnPlayEnd(callback) {
    this.onPlayEnd = callback;
  }
  
  /**
   * 设置错误回调
   * @param {Function} callback - 回调函数
   */
  setOnError(callback) {
    this.onError = callback;
  }
  
  /**
   * 获取当前录音文件路径
   * @return {string} 录音文件路径
   */
  getAudioFilePath() {
    return this.tempFilePath;
  }
  
  /**
   * 销毁实例，释放资源
   */
  destroy() {
    this.innerAudioContext.destroy();
  }
}